import cv2
import numpy as np

icol = (0, 143, 108, 59, 255, 255)
font = cv2.FONT_HERSHEY_SIMPLEX  # 设置字体样式

def nothing(*args):
    pass


cv2.namedWindow('color_test')
cv2.createTrackbar('low_Hue', 'color_test', icol[0], 255, nothing)
cv2.createTrackbar('low_Sat', 'color_test', icol[1], 255, nothing)
cv2.createTrackbar('low_Val', 'color_test', icol[2], 255, nothing)
cv2.createTrackbar('high_Hue', 'color_test', icol[3], 255, nothing)
cv2.createTrackbar('high_Sat', 'color_test', icol[4], 255, nothing)
cv2.createTrackbar('high_Val', 'color_test', icol[5], 255, nothing)

frame = cv2.imread('PNG/1_Color.png')
cap = cv2.VideoCapture(6)
while True:
    ret, frame = cap.read()
    low_Hue = cv2.getTrackbarPos('low_Hue', 'color_test')
    low_Sat = cv2.getTrackbarPos('low_Sat', 'color_test')
    low_Val = cv2.getTrackbarPos('low_Val', 'color_test')
    high_Hue = cv2.getTrackbarPos('high_Hue', 'color_test')
    high_Sat = cv2.getTrackbarPos('high_Sat', 'color_test')
    high_Val = cv2.getTrackbarPos('high_Val', 'color_test')


    frameBGR = cv2.GaussianBlur(frame, (7, 7), 0)

    cv2.imshow('blurred', frameBGR)

    hsv = cv2.cvtColor(frameBGR, cv2.COLOR_BGR2HSV)

    colorLow = np.array([low_Hue, low_Sat, low_Val])
    colorHigh = np.array([high_Hue, high_Sat, high_Val])
    mask = cv2.inRange(hsv, colorLow, colorHigh)

    cv2.imshow('mask-plain', mask)

    kernal = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7))
    mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernal)
    mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernal)
    edges = cv2.Canny(mask, 50, 100)  # 边缘识别

    circles = cv2.HoughCircles(
        edges, cv2.HOUGH_GRADIENT, 1, 100, param1=100, param2=10, minRadius=10, maxRadius=50)
    if circles is not None:  # 如果识别出圆
        for circle in circles[0]:
            #  获取圆的坐标与半径
            x = int(circle[0])
            y = int(circle[1])
            r = int(circle[2])
            cv2.circle(frame, (x, y), r, (0, 0, 255), 3)  # 标记圆
            cv2.circle(frame, (x, y), 3, (255, 255, 0), -1)  # 标记圆心
            text = 'x:  ' + str(x) + ' y:  ' + str(y)
            cv2.putText(frame, text, (10, 30), font, 1, (0, 255, 0), 2, cv2.LINE_AA, 0)  # 显示圆心位置
    else:
        # 如果识别不出，显示圆心不存在
        cv2.putText(frame, 'x: None y: None', (10, 30), font, 1, (0, 255, 0), 2, cv2.LINE_AA, 0)

    cv2.imshow('mask', mask)
    cv2.imshow('edges',edges)
    cv2.imshow('frame', frame)
    result = cv2.bitwise_and(frame, frame, mask=mask)
    cv2.imshow('color_test',result)

    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

cv2.destroyWindow()
